package com.cwt_taxi_xa;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.db.bll.EventBiz;
import com.cwt_taxi_xa.model.EventInfo;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 事件界面
 * @author wlh
 *
 */
public class EventList extends CWTBaseActivity implements OnItemClickListener,
		OnScrollListener,OnTouchListener {
	private static final String TAG = "EventList";
	public TextView tips;
	public ListView message_listView;
	public List<EventInfo> list;
	public int currentPage = 1;// 默认第一页
	public static final int lineSize = 5;// 每次显示4条
	public int pageSize = 1; // 总多少页
	public int allRecord = 0;// 总记录
	private int lastItem;
	public View view;// 底部视图，加载更多
	TextView loadmore;
	public EventAdapter eventAdapter;
	public static EventList instance = null;
	private EventBiz eventBiz;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.event_list);

		try {
			setupViews();
			addListener();
			initData();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setupViews() {
		// TODO Auto-generated method stub
		view = getLayoutInflater().inflate(R.layout.loadmore, null);
		tips = (TextView) this.findViewById(R.id.q_tip);
		message_listView = (ListView) this
				.findViewById(R.id.message_listView);
		message_listView.addFooterView(view);
		loadmore = (TextView)view.findViewById(R.id.moreText);
	}

	private void addListener() {
		// TODO Auto-generated method stub
		message_listView.setOnScrollListener(this);
		message_listView.setOnTouchListener(this);
		message_listView.setOnItemClickListener(this);
	}

	private void initData() {
		// TODO Auto-generated method stub
		instance = EventList.this;
		eventBiz = new EventBiz(this);
		// 获取总记录
		allRecord = eventBiz.getCount();
		eventAdapter = new EventAdapter(this);
		// 获取总页数
		pageSize = (allRecord + lineSize - 1) / lineSize;
		tips.setOnTouchListener(this);
		queryMessageCenter();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 查找第一次的数据
	 */
	public void queryMessageCenter() {
		new AsyncTask<String, Integer, Long>() {
			@Override
			protected Long doInBackground(String... params) {
				ArrayList<EventInfo> listCache = eventBiz.getEvents(currentPage, lineSize);
				if(listCache != null && listCache.size() != 0){
					if(list == null){
						list = new ArrayList<EventInfo>();
					}
					list.addAll(listCache);
				}
				return 1L;
			}

			@Override
			protected void onPostExecute(Long result) {
				if (list != null && list.size() > 0) {
					tips.setVisibility(View.GONE);
					eventAdapter.setData(list);
					if(currentPage == 1){
						message_listView.setAdapter(eventAdapter);
					}else{
						eventAdapter.notifyDataSetChanged();
					}

					//把未读信息变为已读
					//						nh.updateMessageCenter();

					if (currentPage == pageSize) {
						message_listView.removeFooterView(view);
					}else{
						loadmore.setText(Constants.LOAD_MORE);
					}
				} else {
					tips.setText("暂无事件信息!");
					tips.setVisibility(View.VISIBLE);
				}
			}
		}.execute();
	}
	/**
	 * 各个item点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		EventInfo info = eventAdapter.getItem(arg2);
		Intent intent = new  Intent();
		//跳转到详细页面
		intent.setClass(EventList.this, EventActivity.class);
		intent.putExtra("info", info);
		startActivity(intent);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
						 int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount - 1; // 统计是否到最后
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (lastItem == eventAdapter.getCount() && currentPage < pageSize
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			currentPage++;
			// 设置显示位置
			loadmore.setText(Constants.LOADING);
			message_listView.setSelection(lastItem);
			// 增加数据
			queryMessageCenter();
		}

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		instance = null;
	}

	public class EventAdapter extends BaseAdapter{
		private static final String TAG = "MessageAdapter.";
		public Context context;
		private LayoutInflater mInflater=null;
		private List<EventInfo> list;
		private EventInfo obj;

		public EventAdapter(Context context) {
			this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if(null!=list&&list.size()>0){
				return list.size();
			}

			return 0;
		}

		public void setData(List<EventInfo> list) {
			this.list = list;
		}

		@Override
		public EventInfo getItem(int position) {
			if(position>=list.size()) position = list.size()-1;
			return list.get(position);
		}

		public void addItems(List<EventInfo> nlist) {
			for (int i = 0; i < nlist.size(); i++) {
				this.list.add(nlist.get(i));
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {
				if(convertView == null){
					convertView = mInflater.inflate(R.layout.message_list_item,null );
				}
				TextView text = (TextView) convertView.findViewById(R.id.message);
				TextView create_time = (TextView) convertView.findViewById(R.id.create_time);
				obj = list.get(position);
				text.setText(obj.getText());
				create_time.setText(DateUtil.getShowTime(obj.getCreatTime()));
				if(obj.getIsDone() == 1){
					text.setTextColor(Color.parseColor("#ffffff"));
				}else{
					text.setTextColor(Color.parseColor("#00FF00"));
				}
				return convertView;

			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e), e);
				e.printStackTrace();
				return null;
			}

		}
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}
}
